package com.desay.pangoo.itmt.controller.rag;


import cn.hutool.core.collection.CollUtil;
import com.desay.pangoo.common.lite.lang.web.BusinessException;
import com.desay.pangoo.common.lite.lang.web.CommonResponse;
import com.desay.pangoo.common.lite.lang.web.PangooWebConstant;
import com.desay.pangoo.common.lite.spring.web.ControllerCommonUtils;
import com.desay.pangoo.itmt.controller.vo.rag.req.UpdateChatTitleReqVo;
import com.desay.pangoo.itmt.controller.vo.rag.req.UpdateMessageContentReqVo;
import com.desay.pangoo.itmt.controller.vo.rag.req.VoteMessageReqVo;
import com.desay.pangoo.itmt.controller.vo.rag.resp.ChatRespVo;
import com.desay.pangoo.itmt.controller.vo.rag.req.ChatWithAiRequestVo;
import com.desay.pangoo.itmt.controller.vo.rag.resp.HistoryRespVo;
import com.desay.pangoo.itmt.controller.vo.rag.resp.HotProblemVo;
import com.desay.pangoo.itmt.enums.AiVoteEnum;
import com.desay.pangoo.itmt.enums.ExceptionCodeEnum;
import com.desay.pangoo.itmt.service.AIChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.util.List;

/**
 * AI 智能问答
 * @author uids1175
 */
@RestController
@Api(tags = "RAG AI智能问答模块")
@RequestMapping(value = "/rag")
@Validated
@Log4j2
public class AIChatController {

    @Autowired
    private AIChatService aiChatService;


    @GetMapping("/chats")
    @ApiOperation(value = "获取全部历史聊天会话", notes = "")
    public ResponseEntity<Object> listAllChat() {
        //获取用户ID
        String userId = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_ID);
        // 获取历史聊天会话
        List<ChatRespVo> chatRespVoList = aiChatService.listChats(userId);
        return new ResponseEntity<>(CommonResponse.success(chatRespVoList), HttpStatus.OK);
    }

    @PostMapping("/chats/new")
    @ApiOperation(value = "创建一个新的聊天会话", notes = "")
    public ResponseEntity<Object> createNewChat() {
        //获取用户ID
        String userId = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_ID);
        // 返回新建的聊天会话
        ChatRespVo newChat = aiChatService.createNewChat(userId);
        return new ResponseEntity<>(CommonResponse.success(newChat), HttpStatus.OK);
    }

    @GetMapping("/chat/{chatId}")
    @ApiOperation(value = "获取指定聊天会话下历史聊天记录", notes = "")
    public ResponseEntity<Object> listMessagesByChatId(@PathVariable("chatId") Long chatId) {
        // 根据chatId获取该会话下的历史聊天记录
        HistoryRespVo historyVo = aiChatService.listMessagesByChatId(chatId);
        long end = System.currentTimeMillis();
        return new ResponseEntity<>(CommonResponse.success(historyVo), HttpStatus.OK);
    }

    @PostMapping("/chat/completion")
    @ApiOperation(value = "发送消息，回答由AI生成", notes = "")
    public ResponseEntity<StreamingResponseBody> chatWithAi(@RequestBody ChatWithAiRequestVo requestVO) {
        //参数校验
        if (requestVO.getChatId() == null || CollUtil.isEmpty(requestVO.getMessages())) {
            throw new BusinessException(ExceptionCodeEnum.RAG_PARAMS_ERROR);
        }
        // 返回Ai生成的内容
        return aiChatService.aiCompletion(requestVO.getMessages(), requestVO.getChatId(), requestVO.getLang());

    }

    @PostMapping("/chat/summary")
    @ApiOperation(value = "由AI总结内容", notes = "")
    public ResponseEntity<StreamingResponseBody> aiSummary(@RequestBody ChatWithAiRequestVo requestVO) {
        //参数校验
        if (requestVO.getChatId() == null || CollUtil.isEmpty(requestVO.getMessages())) {
            throw new BusinessException(ExceptionCodeEnum.RAG_PARAMS_ERROR);
        }
        // 返回Ai生成的内容
        return aiChatService.aiSummary(requestVO.getMessages().get(0), requestVO.getChatId(), requestVO.getLang());
    }

    @GetMapping("/top/problem")
    @ApiOperation(value = "获取前10个热点问题", notes = "")
    public ResponseEntity<Object> getTop10HotProblem() {
        // 返回前10个热度最高的问题
        List<HotProblemVo> top10HotProblem = aiChatService.getTop10HotProblem();
        return new ResponseEntity<>(CommonResponse.success(top10HotProblem),HttpStatus.OK);
    }


    @PostMapping("/vote/like")
    @ApiOperation(value = "对指定的AI回答的Message进行点赞", notes = "")
    public ResponseEntity<Object> likeMessage(@RequestBody VoteMessageReqVo voteMessageReqVo) {
        // 点赞
        aiChatService.saveVoteStatusAndComment(AiVoteEnum.LIKE.getCode(),voteMessageReqVo.getMessageId(),voteMessageReqVo.getComment());
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }

    @PostMapping("/vote/dislike")
    @ApiOperation(value = "对指定的AI回答的Message进行点踩", notes = "")
    public ResponseEntity<Object> dislikeMessage(@RequestBody VoteMessageReqVo voteMessageReqVo) {
        // 点踩
        aiChatService.saveVoteStatusAndComment(AiVoteEnum.DISLIKE.getCode(),voteMessageReqVo.getMessageId(),voteMessageReqVo.getComment());
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }

    @PostMapping("/vote/reset/{messageId}")
    @ApiOperation(value = "根据MessageId对对应的Message进行取消点赞/点踩的操作", notes = "")
    public ResponseEntity<Object> resetMessage(@PathVariable("messageId") Long messageId) {
        // 重置
        aiChatService.saveVoteStatusAndComment(AiVoteEnum.RESET.getCode(), messageId,null);
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }

    @PostMapping("/message/clear")
    @ApiOperation(value = "清空指定聊天会话下的历史消息", notes = "")
    public ResponseEntity<Object> clearMessage(Long chatId) {
        // 点踩
        aiChatService.clearHistoryMessage(chatId);
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }

    @PutMapping("/messages")
    @ApiOperation(value = "修改指定的消息内容", notes = "")
    public ResponseEntity<Object> updateMessage(@RequestBody UpdateMessageContentReqVo vo) {
        // 点踩
        aiChatService.updateAiMessageContent(vo);
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }

    @PutMapping("/chats")
    @ApiOperation(value = "修改指定聊天会话的标题", notes = "")
    public ResponseEntity<Object> updateChatTitle(@RequestBody UpdateChatTitleReqVo vo) {
        // 更新会话标题
        aiChatService.updateChatTitle(vo);
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }

    @DeleteMapping("/chats/{chatId}")
    @ApiOperation(value = "根据聊天会话Id删除整个会话包括其中的历史消息", notes = "")
    public ResponseEntity<Object> deleteChatById(@PathVariable("chatId") Long chatId) {
        // 删除会话
        aiChatService.deleteChatById(chatId);
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }

    @DeleteMapping("/messages/{messageId}")
    @ApiOperation(value = "根据某个消息Id删除这个消息及其子消息", notes = "")
    public ResponseEntity<Object> deleteMessageById(@PathVariable("messageId") Long messageId) {
        // 删除消息以及子消息
        aiChatService.deleteMessageById(messageId);
        return new ResponseEntity<>(CommonResponse.success(),HttpStatus.OK);
    }


}
